package monkey;

public class SeqList<T> implements MList<T> {
    protected Object[] element; // 对象数组，保护成员

    protected int len; // 顺序表长度，记载元素个数

    public SeqList(int size) {
        this.element = new Object[size]; // 若size<0，抛出异常
        this.len = 0;
    }

    public SeqList(Object[] element) {
        this.element = element;
        this.len = element.length;
    }


    public SeqList() {
        this(64);
    }

    @Override
    public boolean isElpmy() {

        return this.len==0;
    }

    @Override
    public T get(int i) {
        if (i >= 0 && i < this.len) {

            return (T) this.element[i];
        }

        return null;
    }

    @Override
    public void set(int i, T x) {
        if (x == null)
            return; // 不能设置空对象
        if (i >= 0 && i < this.len)
            this.element[i] = x;
        else        //i若不符合，则报错
            throw new IndexOutOfBoundsException(i + ""); // 抛出序号越界异常
    }

    public String toString() {
        String str = "顺序表: (";
        if (this.len > 0)
            str += this.element[0].toString();
        for (int i = 1; i < this.len; i++)
            str += ", " + this.element[i].toString();
        return str + ")" ; // 空表返回()

    }


    @Override
    public void insert(int i, T x) throws Exception {
        if(x==null){
            return; //不插入空对象
        }
        if(i<0 || i>this.len){
            throw new Exception("插入位置不合法");
        }
        if (i==this.len){
            Object[] temp=this.element;  //先存放原数组
            this.element=new Object[temp.length*2];  //重新申请一个容量更大的数组
            for (int j = 0; j < temp.length; j++) // 复制数组元素，O(n)
                this.element[j] = temp[j];
        }
        for(int j=this.len-1;j>=i;j--){
            this.element[j+1]=this.element[j];    //元素后移
        }
        this.element[i] = x;
        // 增加表仓储
        this.len++;


    }

    @Override
    public T remove(int i) throws Exception {
        if(this.len==0 || i<0 || i>=this.len){
            throw  new Exception("删除位置不合法");
        }
        T  old= (T) this.element[i];
        for(int j=i;j<this.len-1;j++){
            this.element[j]=this.element[j+1];
        }
        this.element[this.len-1]=null;
        this.len--;
        return null;
    }

    @Override
    public void removeAll() {
        this.len=0;
    }

    @Override
    public int search(T key) {
        for (int i = 0; i < this.len; i++) {
            if (key.equals(this.element[i])){
                return i;
            }
            return -1;
        }
        return 0;
    }


}
